import React from 'react';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import ListGroup from "react-bootstrap/lib/ListGroup";
import ListGroupItem from "react-bootstrap/lib/ListGroupItem";
import Input from "react-bootstrap/lib/Input";
import LeftNav from '../../../../node_modules/material-ui/lib/left-nav';
import Path from '../../lib/path.js';
import Modal from "../../../../node_modules/react-bootstrap/lib/Modal";
import EventProxy from '../../lib/eventproxy.js';
import List from "../component/List.jsx";
import HttpRequest from './../HttpRequest.js';
import Form from '../../src/component/formElement/Form.jsx';
import DropdownButton from 'react-bootstrap/lib/DropdownButton';
import MenuItem from 'react-bootstrap/lib/MenuItem';

var CertManageTab = React.createClass({
    getInitialState: function () {
        return ({
            open: false,
            current_project: this.props.current_project, //当前项目
            ListData: [], //证书数据
            ListItems: [], //左侧证书列表
            current_selected: null //当前选中证书
        });
    },
    componentWillReceiveProps: function (newProps) {
        this.setState({
                current_project: newProps.current_project,
            }, this.componentWillMount
        );
    },

    componentWillMount: function () {
        var ob = this;
        HttpRequest.getCerts(this.state.current_project._id).success(function (result) {
            if (0 == result.code) {
                ob.setState({
                    ListData: result.data
                }, ob._renderList);
            }
        }.bind(this)).error(function (msg) {
            console.log("获取证书信息失败：" + msg);
        });
    },

    onItemSelected: function (item) {
        this.setState({current_selected: item});
    },
    removeCert: function (cert_id) {
        var body = {
            cert_id: cert_id,
            project_id: this.state.current_project._id
        };
        confirm("确定删除？",function(){
                HttpRequest.removeCert(body).success(function (resp) {
                    if (resp.code != 500) {
                        this.componentWillMount();
                    } else {
                        toastr.error(null, "删除失败");
                    }
                }.bind(this)).error(function () {
                    toastr.error(null, "删除失败");
                });
        }.bind(this));
    },
    addCertAndroid: function () {
        var count = 0;
        if (count == 0) {
            count = "";
        }
        this.state.ListData.map(function (cert) {
            if (cert.name == '新建Android证书' + count) {
                count++;
            }
        });
        var name = '新建Android证书' + count;
        var newAndroidCert = {
            name: name,
            type: 'Android',
            extend_info: {
                "KeyStoreSecret": null,
            },
            files: {
                "keystoreFile": {
                    "file_path": null,
                    "file_name": null
                }
            }
        };
        HttpRequest.addCert(this.state.current_project._id, newAndroidCert).success(function (msg) {
            if (msg.data.success) {
                this.componentWillMount();
            }
        }.bind(this)).error(function (msg) {
            toastr.error(null, "证书添加失败");
        });
    },

    addCertiOS: function () {
        var count = 0;
        if (count == 0) {
            count = "";
        }
        this.state.ListData.map(function (cert) {
            if (cert.name == '新建iOS证书' + count) {
                count++;
            }
        });
        var name = '新建iOS证书' + count;
        var newIOSCert = {
            name: name,
            type: 'IOS',

            extend_info: {
                "provisionID": null,
                "P12Password": null
            },
            files: {
                "provisionFile": {
                    "file_path": null,
                    "file_name": null
                },
                "P12File": {
                    "file_path": null,
                    "file_name": null
                }
            },
        };
        HttpRequest.addCert(this.state.current_project._id, newIOSCert).success(function (msg) {
            if (msg.data.success) {
                this.componentWillMount();
            }
        }.bind(this)).error(function (msg) {
            console.log(msg);
        });

    },
    _renderList: function () {
        this.setState({
            List: <List ListData={this.state.ListData}
                        ItemStyle = {{cursor: "pointer"}}
                        SelectedItemStyle={{backgroundColor:"#f3f3f3",cursor: "pointer"}}
                        onItemSelected={this.onItemSelected}
                        itemDeleted={this.removeCert}
                        ifEmpty={<span style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有证书！ </span>}
                        IconMap={[{type:"Android",icon:<img src="/res/image/android.png" style={{marginTop:"-5px"}}/>},{type:"IOS",icon:<img src="/res/image/ios.png" style={{marginTop:"-5px"}}/>}]}
            />
        });
        if (this.state.ListData.length > 0) {
            this.setState({
                current_selected: this.state.ListData[this.state.ListData.length - 1]
            })
        }
    },
    saveEdit: function () {
        this.componentWillMount();
    },
    render: function () {
        var content_pageRight = null;
        if (this.state.ListData && this.state.ListData.length > 0) {
            content_pageRight = <CertDetailInfo
                update={this.saveEdit}
                current_selected={this.state.current_selected} certs={this.state.ListData}/>
        } else {
            content_pageRight = <div style={{textAlign:"center"}}>
                <image src="/res/image/zhengshu.png" style={{marginTop:"20px"}}/>
                <div style={{color:"#969696",paddingTop:"20px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有证书！
                </div>
            </div>
        }
        return (
            <div style={{height:"100%"}}>
                <div className="content_pageLeft">
                    <span className="info_title" style={{paddingLeft:"30px"}}>证书列表</span>
                    <DropdownButton bsStyle="primary"
                                    style={{backgroundColor:"#555",height: "25px",paddingTop: "2px"}}
                                    title="新建" id="new_product_config">
                        <MenuItem eventKey="ANDROID" onClick={this.addCertAndroid}>安卓证书</MenuItem>
                        <MenuItem eventKey="IOS" onClick={this.addCertiOS}>ios证书</MenuItem>
                    </DropdownButton>
                    <div style={{overflowY:"auto",height:"100%",maxHeight:"90%",marginTop:"5px"}}>
                        {this.state.List}
                    </div>

                </div>
                <div className="content_pageRight">
                    <div className="info_title">证书信息</div>
                    {content_pageRight}
                </div>
            </div>
        )
    }

});
var CertDetailInfo = React.createClass({

    getInitialState: function () {
        return ({
            certs: this.props.certs,
            current_selected: this.props.current_selected
        });
    },
    update: function () {
        this.props.update()
    },
    render() {

        var current_selected = this.props.current_selected;
        if (current_selected) {
            switch (current_selected.type) {
                case 'Android':
                    return <CertDetailInfo_Android update={this.update} detailInfo={current_selected}/>;
                case 'IOS':
                    return <CertDetailInfo_iOS update={this.update} detailInfo={current_selected}/>;
                default:
                    return <div></div>;
            }
        }
        return <div></div>;

    }
});

class CertDetailInfo_iOS extends React.Component {

    textChange() {
        this.props.detailInfo.name = this.refs["name"].getValue();
        this.props.detailInfo.P12Password = this.refs["P12Password"].getValue();
        this.props.detailInfo.provisionID = this.refs["provisionID"].getValue();
        this.setState({save: false});
    };

    save(form) {
        HttpRequest.modifyCert(this.props.detailInfo._id, form).success(function (msg) {
            toastr.success(null, "证书修改成功");
            this.props.update();
        }.bind(this)).error(function (msg) {
            toastr.error(null, "证书修改失败");
        });
    };

    render() {
        var certInfo = this.props.detailInfo;
        var filesInfo = certInfo.files;

        var formData = [
            {
                type: "label",
                title: "证书类型",
                name: "Type",
                icons: [{type: "Android", icon: "/res/image/android.png"}, {type: "IOS", icon: "/res/image/ios.png"}],
                defaultValue: certInfo.type
            },
            {
                type: "input",
                title: "证书名称",
                name: "CertName",
                defaultValue: certInfo.name
            },
            {
                type: "file",
                title: "P12证书文件",
                name: "P12File",
                defaultValue: filesInfo.P12File.file_name
            },
            {
                type: "input",
                title: "P12证书密码",
                name: "P12Password",
                defaultValue: certInfo.extend_info.P12Password
            },
            {
                type: "file",
                title: "授权文件",
                name: "provisionFile",
                defaultValue: filesInfo.provisionFile.file_name
            },
            {
                type: "input",
                title: "授权文件ID",
                name: "provisionID",
                defaultValue: certInfo.extend_info.provisionID
            },
        ];
        return (
            <div style={{marginTop: "20px",height: "calc(100% - 50px)"}}>
                <Form FormData={formData} saveForm={this.save.bind(this)}/>
            </div>
        )
    };
}
;

class CertDetailInfo_Android extends React.Component {

    save(form) {
        HttpRequest.modifyCert(this.props.detailInfo._id, form).success(function (msg) {
            toastr.success(null, "证书修改成功");
            this.props.update();
        }.bind(this)).error(function (msg) {
            toastr.error(null, "证书修改失败");
        });

    };

    render() {
        var certInfo = this.props.detailInfo;
        var formData = [
            {
                type: "label",
                title: "证书类型",
                name: "Type",
                defaultValue: certInfo.type,
                icons: [{type: "Android", icon: "/res/image/android.png"}, {type: "IOS", icon: "/res/image/ios.png"}],
            },
            {
                type: "input",
                title: "证书名称",
                name: "CertName",
                defaultValue: certInfo.name
            },
            {
                type: "file",
                title: "keystore文件",
                name: "keyStoreFile",
                defaultValue: certInfo.files.keystoreFile.file_name
            },
            {
                type: "input",
                title: "keystore密码",
                name: "KeyStoreSecret",
                defaultValue: certInfo.extend_info.KeyStoreSecret
            }
        ];
        return (
            <div style={{marginTop: "20px",height: "calc(100% - 50px)"}}>
                <Form FormData={formData} saveForm={this.save.bind(this)}/>
            </div>
        )

    }
}
;

export default CertManageTab;